package game;

import player.Player;

public class Camera {

	private static final float ACCELERATION_RATIO = 0.03f;
	private static final int MAX_BORDER = 50;

	private float x, y, zoom = 1;
	private boolean followCam = true, lockX, lockY;
	private int width, height, levelWidth, levelHeight;

	public Camera(int width, int height, int levelWidth, int levelHeight){
		this.width = width;
		this.height = height;
		this.levelWidth = levelWidth;
		this.levelHeight = levelHeight;
		if(levelWidth < width + 2*MAX_BORDER){
			x = levelWidth/2f;
			lockX = true;
		}
		if(levelHeight < height + 2*MAX_BORDER){
			y = levelHeight/2f;
			lockY = true;
		}
	}

	public void disableFollowing(){
		followCam = false;
	}

	public void enableFollowing(){
		followCam = true;
	}

	public void forceMoveX(float dx){
		if(!lockX)
			x += dx;
	}

	public void forceMoveY(float dy){
		if(!lockY)
			y += dy;
	}

	public void forceCenter(float cx, float cy){
		if(!lockX)
			x = cx;
		if(!lockY)
			y = cy;
	}

	public void update(Player player){
		if(followCam){
			float dX = player.getX() - x;
			float dY = player.getY() - y;
			forceMoveX(dX * ACCELERATION_RATIO);
			forceMoveY(dY * ACCELERATION_RATIO);
		}
		//check for map borders
		float offsetX = getOffsetX();
		float offsetY = getOffsetY();
		if(!lockX){
			if(offsetX >= MAX_BORDER)
				x = width/2f - MAX_BORDER;
			else if(levelWidth - width + offsetX < -MAX_BORDER)
				x = levelWidth - width + MAX_BORDER + width/2f;
		}
		if(!lockY){
			if(offsetY >= MAX_BORDER)
				y = height/2f - MAX_BORDER;
			else if(levelHeight - height + offsetY < -MAX_BORDER)
				y = levelHeight - height + MAX_BORDER + height/2f;
		}
	}

	public float getCenterX() {
		return x;
	}

	public float getCenterY() {
		return y;
	}

	public float getOffsetX(){
		return width/2f - x;
	}

	public float getOffsetY(){
		return height/2f - y;
	}

	public float getZoom() {
		return zoom;
	}

	public boolean isFollowCam() {
		return followCam;
	}

	public int getWidth() {
		return width;
	}

	public int getHeight() {
		return height;
	}
}
